package com.fengxu.netty.websocket;

import com.fengxu.netty.detectconnect.IdleTestServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.time.LocalDateTime;

// websocket服务器
public class WebSocketServer {

    public void run() throws Exception{
        // 创建线程组
        NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 创建服务器启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 因为是基于Http协议的所有需要加上Http请求的编码/解码器
                        ch.pipeline().addLast(new HttpServerCodec());
                        // 以块的方式写,添加ChunkedWriteHandler
                        ch.pipeline().addLast(new ChunkedWriteHandler());
                        // http传输数据很大时是分段的，所有加上一个聚合数据的处理器
                        ch.pipeline().addLast(new HttpObjectAggregator(8191));
                        // 添加websocket处理器,它的数据是以frame(帧)的形式传递的
                        // 核心功能将http协议升级为ws协议,保持长连接
                        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/test"));
                        // 添加自定义处理器
                        ch.pipeline().addLast(new MyWebSocketHandler());
                    }
                });
        ChannelFuture future = serverBootstrap.bind(8000).sync();
        future.addListener(fu -> {
            if(fu.isSuccess()){
                System.out.println("监听端口8000成功!");
            } else {
                System.out.println("监听端口8000失败！");
            }
        });
        future.channel().closeFuture().sync();
    }

    // 自定义一个基于文本frame的websocket处理器
    private class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
            System.out.println("收到用户消息:"+msg.text());

            // 回复信息
            ctx.writeAndFlush(new TextWebSocketFrame("服务器时间:"+ LocalDateTime.now()+" 消息: "+msg.text()));
        }

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            // LongText是唯一的,ShortText不是唯一的
            System.out.println("有客户端连接!"+ctx.channel().id().asLongText());
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            System.out.println("有客户端断开连接!"+ctx.channel().id().asLongText());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("发生异常:"+cause.getMessage());
            ctx.close();
        }
    }

    public static void main(String[] args) throws Exception {
        new WebSocketServer().run();
    }
}
